package com.njzxw.fs.serverzuul.fitter;


import com.google.gson.Gson;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

@Component
public class PostFilter extends BaseFilter {


    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
//        String url = RequestContext.getCurrentContext().getRequest().getRequestURI();
//        if(!url.contains("/manage/")){
//            return true;
//        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();
        String contentType = "";

        try{
            contentType = request.getContentType();
            if (contentType != null && contentType.contains("application/json")) {
                InputStream stream = context.getResponseDataStream();
                String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
                if (StringUtils.isNotBlank(body)) {
                    Gson gson = new Gson();

                    @SuppressWarnings("unchecked")
                    Map<String, String> result = gson.fromJson(body, Map.class);

                    result.put("terrace",String.valueOf(context.get("terrace")));
                    logger.info("result:"+result);

                    body = gson.toJson(result);
                    context.setResponseBody(body);
//                    context.setResponseStatusCode(200);
                }
            }
            context.setSendZuulResponse(true); //对请求进行路由
            context.set("isSuccess", true);//打上标志位
            return null;
        }catch (Exception e){
            logger.error("网关权健出现错误", e);
            setReturnErrorJsonMap(context,response,false,200,"系统出现未知错误，请稍后再试");
        }

        return null;
    }
}